use std::io;

use actix_session::{Session, SessionMiddleware};
use actix_session::storage::CookieSessionStore;
use actix_web::{App, dev, Error, HttpResponse, HttpServer, Result, web};
use actix_web::cookie::Key;
use actix_web::http::{header, StatusCode};
use actix_web::middleware::{ErrorHandlerResponse, ErrorHandlers};

async fn index(session: Session) -> Result<HttpResponse, Error> {
    if let Some(count) = session.get::<i32>("counter")? {
        session.insert("counter", count + 1)?;
    } else {
        session.insert("counter", 1)?;
    }

    Ok(HttpResponse::Ok().body(format!(
        "Count is {:?}",
        session.get::<i32>("counter")?.unwrap()
    )))
}

fn add_error_header<B>(mut res: dev::ServiceResponse<B>)->Result<ErrorHandlerResponse<B>>{
    res.response_mut()
        .headers_mut()
        .insert(
            header::CONTENT_TYPE,
            header::HeaderValue::from_static("Error"),
        );

    Ok(ErrorHandlerResponse::Response(res.map_into_left_body()))
}

#[actix_web::main]
async fn main() -> io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .wrap(
                // 注册自定义错误处理程序
                ErrorHandlers::new()
                    .handler(StatusCode::INTERNAL_SERVER_ERROR,add_error_header),
            )
            .service(web::resource("/").to(index))
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}
